#include "dialogsearch.h"
#include "ui_dialogsearch.h"

DialogSearch::DialogSearch(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogSearch)
{
    ui->setupUi(this);

    connect(ui->tableWidget, SIGNAL(cellChanged(int,int)), this, SLOT(callChanged(int,int)));
}

DialogSearch::~DialogSearch()
{
    delete ui;
}

int DialogSearch::pos()
{
    if (ui->radioButtonCurrent->isChecked())
    {
        return 1;
    }

    return 0;
}

QByteArray DialogSearch::content()
{
    if (ui->tabWidget->currentIndex() == 0)
    {
        return ui->textEdit->toPlainText().toLatin1();
    }
    else if (ui->tabWidget->currentIndex() == 1)
    {
        bool end = false;
        QByteArray bytes;

        for (int i=0; i<4; i++)
        {
            for (int j=0; j<8; j++)
            {
                bool ok = false;
                QTableWidgetItem *item = ui->tableWidget->item(i, j);
                if (item)
                {
                    int byte = item->text().toInt(&ok, 16);
                    if (!ok) {
                        end = true;
                        break;
                    }

                    byte = byte & 0xFF;
                    bytes.append((char)byte);
                }
            }

            if (end)
            {
                break;
            }
        }

        return bytes;
    }

    return QByteArray();
}


void DialogSearch::callChanged(int r, int c)
{
    bool needReset = false;
    QString text = ui->tableWidget->item(r, c)->text();
    if (text.isEmpty())
    {
        return;
    }

    if (text.length() > 2)
    {
        text = text.right(2);
        needReset = true;
    }

    bool ok = false;
    int val = text.toInt(&ok, 16);
    if (!ok)
    {
        needReset = true;
        text = "";
    }

    if (val < -127 && val > 127)
    {
        needReset = true;
        text = "FF";
    }

    if (needReset)
    {
        ui->tableWidget->item(r, c)->setText(text);
    }
}


int DialogSearch::searchType()
{
    return ui->tabWidget->currentIndex();
}
